package com.springcloud.gateway.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsConfig {

    /**
     * gateway中跨域过滤器是CorsWebFilter，springboot中的是CorsFilter
     *
     * @return
     */
    @Bean
    public CorsWebFilter corsWebFilter() {

        //跨域配置类，配置允许哪些请求源、请求方式、请求头跨域访问
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedMethod("*");
        //addAllowedOrigin：在2.4版本之前的方法，在2.4版本以后是addAllowedOriginPattern
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

        // 跨域的路径映射，允许哪些路径使用跨域配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 响应式的跨域过滤器
        return new CorsWebFilter(source);
    }
}
